import React from 'react'
import { Toast, TextareaItem, Modal } from 'antd-mobile'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import { actions as newsActionCraetors } from '../../redux/modules/news'
import getQuery from '../../helpers/getQuery'
import config from '../../../config';
import './discuss.less'

const imgPath = 'http://file.winkse.com/Upload/Common/Salesman/qq'
const userId = getQuery('userId')

const faceList = () => {
  var list = []
  for(var i = 0; i < 60; i ++) {
    list.push(`${imgPath}/${i}.png`)
  }
  return list
}

class Detail extends React.PureComponent {

  static contextTypes = {
    router: React.PropTypes.object.isRequired
  }

  state = {
    visible: false,
    list: [],
    title: '',
    value: ''
  }

  componentWillMount() {
    const id = this.props.params.id

    this.fetchDetail(id)
    this.fetchDisList({
      articleId: id,
      pageIndex: 1,
      pageSize: 20,
      userId: userId 
    })
  }

  componentDidMount() {
    const page = document.getElementById('discuss-page')
    const content = document.getElementById('inner-wrap')
    page.scrollTo(0, 0)
    page.onscroll = () => {
      //为了保证兼容性，这里取两个值，哪个有值取哪一个
      //scrollTop就是触发滚轮事件时滚轮的高度
      var scrollTop = page.scrollTop || document.body.scrollTop;
      var pageH = page.clientHeight
      var contentH = content.clientHeight
      // 滚动到50公分左右作判断
      if (contentH - pageH > scrollTop + 50) {
        if (this.props.pageIndex < this.props.pageCount) {
          this.fetchDisList({
            articleId: id,
            pageIndex: this.props.pageIndex++,
            pageSize: 20,
            userId: userId
          })
        } 
      }
    }
  }

  render() {
    return <section className="discuss-page" id="discuss-page">
      <div className="inner-wrap" id="inner-wrap">
        <div className="title">{this.state.title}</div>
        <div className="content">
          <TextareaItem
            placeholder="你想说的啥"
            value={this.state.value}
            onChange={this.handleChange.bind(this)}
            count={2000}
            id="textarea"
            autoHeight
          />
          <i className="iconfont icon-haoping" onClick={this.handleVisible.bind(this)}/>
        </div>
        {
          this.state.visible && <div className="face-wrap">
            {faceList().map((item,i) => <img key={i} src={item} onClick={this.handleFace.bind(this, i)}/>)}
          </div>
        }

        <div className="btn" onClick={this.handleSubmit.bind(this)}>留言</div>

        {
          this.props.list.length > 0  && <div className="discuss-list">
            <div className="header">
              <span>我的留言</span>
            </div>
            {
              this.props.list.map((item, i) => <div className="item" key={i}>
                <div className="avator"><img src={item.WxImgUrl}/></div>
                <div className="content">
                  <div className="name">{item.CreateName}<span className="action" onClick={this.handleDelete.bind(this, item.Id)}>删除</span></div>
                  <div className="remark" dangerouslySetInnerHTML={{ __html: this.encodeContent(item.Comment) }}></div>
                </div>
              </div>)
            }
          </div>
        }
      </div>
    </section>
  }

  fetchDetail(id) {
    this.props.actions.fetchDetail({id}, json => {
      if (json.IsSuccess) {
        this.setState({
          title: json.Data.Title
        })
      } else {
        Toast.info(json.Msg, 1);
      }
    })
  }


  fetchDisList(params) {
    this.props.actions.fetchDisList(params, json => {
      if (!json.IsSuccess) {
        Toast.info(json.Msg, 1);
      }
    })
  } 

  handleChange(value) {
    this.setState({
      value
    })
  }

  handleSubmit() {
    const id = this.props.params.id
    this.props.actions.addDis({
      "ArticleId": id,
      "Comment": this.state.value,
      "UserId": userId
    }, json => {
      if (json.IsSuccess) {
        Toast.success('留言成功')
        this.setState({
          value: '',
          visible: false
        })
        this.fetchDisList({
          articleId: id,
          pageIndex: 1,
          pageSize: 20,
          userId: userId 
        })
      } else {
        Toast.info(json.Msg, 1);
      }
    })
  }

  handleDelete(id) {
    this.props.actions.deleteDis({id}, json => {
      if (json.IsSuccess) {
        Toast.success('删除成功')
        this.fetchDisList({
          articleId: this.props.params.id,
          pageIndex: 1,
          pageSize: 20,
          userId: userId 
        })
      } else {
        Toast.info(json.Msg, 1);
      }
    })
  }

  handleFace(i) {
    const textArea = document.getElementById('textarea')
    const pos = this.getCursorPos(textArea)
    
    const prefix = textArea.value.substr(0, pos)
    const suffix = textArea.value.substr(pos)

    const _value = `${prefix}[${i}]${suffix}`

    textArea.value = _value

    this.setState({
      value: _value
    })
    
  }

  handleVisible() {
    this.setState({
      visible: !this.state.visible
    })
  }

  getCursorPos(pTextArea) {
  	var cursurPosition = -1;
  	if (pTextArea.selectionStart) {//非IE浏览器
      cursurPosition = pTextArea.selectionStart;
    } else {//IE
      if (document.selection) {
        var range = document.selection.createRange();
        range.moveStart("character",-pTextArea.value.length);
        cursurPosition=range.text.length;
      } else {
        cursurPosition=window.cursurPosition;
      }
    }

    // 存储在window 下。避免input失去焦点无法找到上次光标位置
    window.cursurPosition = cursurPosition

    return cursurPosition;
  }

  encodeContent(str) {
    const reg = /\[([^\]]+)\]/g;
    str = str.replace(reg, function(m, n) {
      if (n > 0 && n < 60) {
        return `<img src='${imgPath}/${n}.png' />`
      } else {
        return m
      }
    });

    return str
  }

}

const stateToProps = state => ({
  ...state.news
})

const dispatchToProps = dispatch => ({
  actions: bindActionCreators(newsActionCraetors, dispatch)
})

export default connect(stateToProps, dispatchToProps)(Detail);
